/**
 * 音频控制功能模块
 * 提供网站范围内统一的音频播放功能
 */

// 当前正在播放的音频元素
let currentlyPlayingAudio = null;

/**
 * 播放音频文件
 * @param {string} audioId - 要播放的音频元素的ID
 */
function playAudio(audioId) {
    const audio = document.getElementById(audioId);
    if (!audio) {
        console.error(`音频元素 ${audioId} 不存在`);
        return;
    }
    
    // 如果有其他音频正在播放，先停止
    if (currentlyPlayingAudio && currentlyPlayingAudio !== audio) {
        currentlyPlayingAudio.pause();
        currentlyPlayingAudio.currentTime = 0;
        removePlayingIndicator(currentlyPlayingAudio.id);
    }
    
    // 播放当前音频
    audio.currentTime = 0;
    const playPromise = audio.play();
    
    if (playPromise !== undefined) {
        playPromise.then(() => {
            // 播放成功
            currentlyPlayingAudio = audio;
            addPlayingIndicator(audioId);
        }).catch(error => {
            console.error('音频播放失败:', error);
            removePlayingIndicator(audioId);
        });
    }
}

/**
 * 为对应的音频按钮添加正在播放的指示器
 * @param {string} audioId - 音频元素的ID
 */
function addPlayingIndicator(audioId) {
    const buttons = document.querySelectorAll(`.audio-btn[data-audio-id="${audioId}"]`);
    buttons.forEach(button => {
        button.classList.add('audio-playing');
    });
}

/**
 * 移除音频按钮的播放指示器
 * @param {string} audioId - 音频元素的ID
 */
function removePlayingIndicator(audioId) {
    const buttons = document.querySelectorAll(`.audio-btn[data-audio-id="${audioId}"]`);
    buttons.forEach(button => {
        button.classList.remove('audio-playing');
    });
}

/**
 * 初始化所有音频按钮
 */
function initializeAudioButtons() {
    const audioButtons = document.querySelectorAll('.audio-btn');
    
    // 为每个音频按钮添加点击事件
    audioButtons.forEach(button => {
        const audioId = button.getAttribute('data-audio-id');
        if (audioId) {
            button.addEventListener('click', function(event) {
                event.preventDefault();
                playAudio(audioId);
            });
        }
    });
    
    // 为所有音频元素添加结束事件监听
    document.querySelectorAll('audio').forEach(audio => {
        audio.addEventListener('ended', function() {
            if (currentlyPlayingAudio === this) {
                currentlyPlayingAudio = null;
                removePlayingIndicator(this.id);
            }
        });
    });
}

// 在文档加载完成后初始化音频按钮
document.addEventListener('DOMContentLoaded', function() {
    initializeAudioButtons();
}); 